using B.S.Data.MES.API.Applications.CangKu.Command;
using B.S.Domain.CangKu;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.CangKu.CommandHandlers
{
    /// <summary>
    /// 根据仓库ID获取库位列表命令处理程序
    /// 实现三级联动中的第一级到第二级：仓库 -> 库位
    /// </summary>
    public class GetKuWeiByCangIdCommandHandler : IRequestHandler<GetKuWeiByCangIdCommand, APIRequst<List<CangKuQU>>>
    {
        private readonly IBaseRepository<CangKuQU> _cangKuQURepository;
        private readonly IBaseRepository<CangKuinfo> _cangKuRepository;

        /// <summary>
        /// 构造函数，注入仓储依赖
        /// </summary>
        /// <param name="cangKuQURepository">库位仓储</param>
        /// <param name="cangKuRepository">仓库仓储</param>
        public GetKuWeiByCangIdCommandHandler(
            IBaseRepository<CangKuQU> cangKuQURepository,
            IBaseRepository<CangKuinfo> cangKuRepository)
        {
            _cangKuQURepository = cangKuQURepository;
            _cangKuRepository = cangKuRepository;
        }

        /// <summary>
        /// 处理根据仓库ID获取库位列表的请求
        /// </summary>
        /// <param name="request">包含仓库ID的命令对象</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含库位列表的API响应</returns>
        public async Task<APIRequst<List<CangKuQU>>> Handle(GetKuWeiByCangIdCommand request, CancellationToken cancellationToken)
        {
            // 首先验证仓库是否存在
            var cangKu =await _cangKuRepository.GetById(request.CangId); // 这里缺少await
            if (cangKu == null)
            {
                return new APIRequst<List<CangKuQU>>
                {
                    Code = RequstCode.失败,
                    Msg = "仓库不存在",
                    Data = new List<CangKuQU>(){}
                };
            }

            // 根据仓库编号查询关联的库位
            var kuWeiList =  _cangKuQURepository.GetAll()
                .Where(k => k.BM == cangKu.CangkuNo)
                .ToList();

            return new APIRequst<List<CangKuQU>>
            {
                Code = RequstCode.成功,
                Msg = "查询成功",
                Data = kuWeiList
            };
        }
    }
}